import Vue from 'vue'
import Router from 'vue-router'
//注册
import MyRegister from '@/views/MyRegister.vue'
//登录
import MyLogin from "@/views/MyLogin.vue"
//首页
import MyHomePage from "@/views/MyHomepage.vue"
import MyHomePageSon from "@/components/MyHomePageSon.vue"
//企业数据
import MyProviceFrist from "@/components/MyFirst.vue"
//服务器数据
import MyFuFirst from "@/components/MySecond.vue"
//省份数据
import MyHeNan from "@/components/MyThird.vue"
//权限管理
import MyPermission from "@/views/MyPermission.vue"
Vue.use(Router)
const routes = [

  // 默认状态
  {
    path: "/",
    redirect: "/Register",
  },
  //默认登录
  {
    path: "/",
    redirect: "/HomepageSon",
  },
  //登录
  {
    path: '/login',
    name: 'login',
    component: MyLogin
  },
  //注册
  {
    path: '/Register',
    name: 'Register',
    component: MyRegister
  }, {
    path: '/HomeIo',
    name: 'HomeIo',
    component: MyHomePage
  },
  //跳转首页
  {
    path: '/Homepage',
    name: 'Homepage',
    component: MyHomePage,
    meta: { requiresAuth: true }, // 标记：需登录才能访问,
    children: [{
      path: "/HomepageSon",
      name: 'HomepageSon',
      component: MyHomePageSon,
      redirect: "/Provice",
      children: [  //省份数据
        {
          path: '/Provice',
          name: 'Provice',
          component: MyProviceFrist,
        }, {
          path: '/Server',
          name: 'Server',
          component: MyFuFirst,
        }, {
          path: '/HeNan',
          name: 'henan',
          component: MyHeNan,
        }],
    },
    //跳转权限管理
    {
      path: '/Permission',
      name: 'Permission',
      component: MyPermission,
    }
    ]
  }]
const router = new Router({ routes });
// 重写 push 方法，捕获重复导航错误
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => {
    // 仅忽略重复导航错误，其他错误继续抛出
    if (err.name === 'NavigationDuplicated') {
      return err;
    }
    return Promise.reject(err);
  });
};
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) {
    const loginData = localStorage.getItem('LoginArr');
    if (loginData) {
      next();
    } else {
      next('/register'); // 未登录跳转到注册页（而非登录页）
    }
  } else {
    next();
  }
});
// 前置守卫
export default router
